package com.chms.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.chms.bean.LoginBean;
import com.chms.service.ILoginService;
import com.chms.serviceImpl.LoginService;
import com.chms.utility.ExceptionMessage;

/**
 * Controller responsible for the Authentication of the user
 * 
 * @author Piyush
 * 
 */
public class LoginController extends BaseController {

	private static final Logger logger = Logger
			.getLogger(LoginController.class);

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("Login controller called");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");

		// Set the bean
		LoginBean loginBean = new LoginBean();
		loginBean.setName(userName);
		loginBean.setPassword(password);
		/*
		 * PdfGenerator pdg=new PdfGenerator(); OutputStream file = new
		 * FileOutputStream(new File("F:\\Test.pdf"));
		 * 
		 * Document document = new Document(PageSize.A4); try {
		 * PdfWriter.getInstance(document, file); document.open();
		 * PdfGenerator.addContent(document); } catch (DocumentException e) { //
		 * TODO Auto-generated catch block e.printStackTrace(); }
		 */

		// document.add(new Paragraph("Hello World, iText"));
		// document.add(new Paragraph(new Date().toString()));

		// call the Service Layer
		ILoginService loginService = new LoginService();
		// Get the response from service layer
		boolean authenticated = loginService.login(loginBean);
		if (authenticated == false) {
			String message = ExceptionMessage.USER_LOGIN_PASSWORD_INVALID;
			request.setAttribute("message", message);
			response.sendRedirect("pages/jsp/login.jsp?message=" + message);
		} else {
			// Set the user in the session
			HttpSession session = request.getSession(false);
			session.setAttribute("user", "authenticated");
			rd = request.getRequestDispatcher("/pages/jsp/welcome.jsp");
			rd.forward(request, response);
		}
		logger.info("Login controller call ended : Response being returned");
	}
}
